package com.example.workflow.controller;

import com.example.workflow.dto.ApprovalHistoryListDto;
import com.example.workflow.dto.ProcessedApprovalListDto;
import com.example.workflow.pojo.LoginUser;
import com.example.workflow.pojo.Result;
import com.example.workflow.service.ApprovalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 审批人员相关接口
 */
@CrossOrigin
@RestController
@RequestMapping("/approval")
@Slf4j
public class ApprovalController {

    @Autowired
    private ApprovalService approvalService;

    /**
     * 获取已处理的审批工单统计数据
     * 返回当前登录用户处理的所有工单统计数据
     *
     * @return 已处理审批工单统计数据
     */
    @GetMapping("/count")
    public Result<ProcessedApprovalListDto> getProcessedApprovalOrders() {
        try {
            // 获取当前用户ID和角色
            Integer userId = getCurrentUserId();
            String role = getCurrentUserRole();
            
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            log.info("获取已处理审批工单统计数据，用户ID: {}, 角色: {}", userId, role);
            
            // 调用服务获取已处理审批工单统计数据
            ProcessedApprovalListDto result = approvalService.getProcessedApprovalOrders(userId, role);
            
            log.info("查询结果: 总数 = {}, 通过 = {}, 拒绝 = {}",
                    result.getTotalCount(), result.getApprovedCount(), result.getRejectedCount());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取已处理审批工单统计数据失败", e);
            return Result.error("获取已处理审批工单统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录审批人员的历史审批工单列表
     * 
     * @return 历史审批工单列表
     */
    @GetMapping("/list")
    public Result<ApprovalHistoryListDto> getApprovalHistoryList() {
        try {
            // 获取当前用户ID和角色
            Integer userId = getCurrentUserId();
            String role = getCurrentUserRole();
            
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            log.info("获取审批历史工单列表，用户ID: {}, 角色: {}", userId, role);
            
            // 调用服务获取审批历史工单列表
            ApprovalHistoryListDto result = approvalService.getApprovalHistoryList(userId, role);
            
            log.info("查询到 {} 条历史审批工单记录", result.getTotalCount());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取审批历史工单列表失败", e);
            return Result.error("获取审批历史工单列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前登录用户ID
     * 
     * @return 当前用户ID，未登录则返回null
     */
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            try {
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                return loginUser.getUserInfo().getId();
            } catch (Exception e) {
                log.warn("获取当前用户ID失败", e);
                return null;
            }
        }
        return null;
    }
    
    /**
     * 获取当前登录用户角色
     * 
     * @return 当前用户角色，未登录则返回null
     */
    private String getCurrentUserRole() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            try {
                LoginUser loginUser = (LoginUser) authentication.getPrincipal();
                return loginUser.getUserInfo().getRole();
            } catch (Exception e) {
                log.warn("获取当前用户角色失败", e);
                return null;
            }
        }
        return null;
    }
} 